package com.test.image;

import com.alibaba.simpleimage.ImageWrapper;
import com.alibaba.simpleimage.util.ImageReadHelper;
import com.alibaba.simpleimage.util.ImageWriteHelper;
import com.test.utils.JsonUtil;
import lombok.AllArgsConstructor;
import lombok.Data;
import net.coobird.thumbnailator.Thumbnails;

import javax.imageio.ImageIO;

import java.awt.*;
import java.awt.image.BufferedImage;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ImageUtil {

    public static byte[] addWaterMark(Image srcImg, List<WriteWord> wordList, String format) throws Exception {
        if (srcImg == null) {
            System.out.println("addWaterMark srcImg is null");
        }
        int srcImgWidth = srcImg.getWidth(null);//获取图片的宽
        int srcImgHeight = srcImg.getHeight(null);//获取图片的高
        // 加水印
        BufferedImage bufImg = new BufferedImage(srcImgWidth, srcImgHeight, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = bufImg.createGraphics();
        // 设置图片背景色是透明的，否则生成的图片可能会出现黑边
        bufImg = g.getDeviceConfiguration().createCompatibleImage(srcImgWidth, srcImgHeight, Transparency.TRANSLUCENT);
        g.dispose();
        g = bufImg.createGraphics();
        g.drawImage(srcImg, 0, 0, srcImgWidth, srcImgHeight, null);
        //-------
        for (WriteWord word : wordList) {
            g.setColor(word.getColor()); //根据图片的背景设置水印颜色
            g.setFont(word.getFont());              //设置字体
            // 使文字显示更清晰，否则文字可能模糊
            g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HRGB);
            System.out.println("setfont22222222");
            //设置水印的坐标
            int x = word.getX();
            int y = word.getY();
            if (x == -1) {
                x = (srcImgWidth - getWatermarkLength(word.getContent(), g)) / 2;
            }
            if (y == -1) {
                y = (srcImgHeight - getWatermarkHeight(word.getContent(), g)) / 2;
            }
            g.drawString(word.getContent(), x, y);  //画出水印
        }
        g.dispose();
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ImageIO.write(bufImg, format, bos);
        byte[] bytes = bos.toByteArray();
        return bytes;
    }

    public static int getWatermarkLength(String waterMarkContent, Graphics2D g) {
        return g.getFontMetrics(g.getFont()).charsWidth(waterMarkContent.toCharArray(), 0, waterMarkContent.length());
    }

    public static int getWatermarkHeight(String waterMarkContent, Graphics2D g) {
        int p = g.getFontMetrics(g.getFont()).getHeight();
        return p;
    }


    public static void main(String[] args) throws Exception {
        String src = "E:\\data\\desktop\\客户协议图片\\e.png";
        String target = "E:\\data\\desktop\\客户协议图片\\person.png";
        List<WriteWord> wordList = new ArrayList<>();
        Font f = new Font("仿宋", Font.PLAIN, 27);

        wordList.add(new WriteWord(260, 505, "乙方", f, Color.BLACK));

        wordList.add(new WriteWord(300, 560, "13866669999", f, Color.RED));
        wordList.add(new WriteWord(300, 5750, "2020-11-03", f, Color.RED));
        wordList.add(new WriteWord(280, 5885, "乙方", f, Color.RED));
        wordList.add(new WriteWord(320, 5953, "法人", f, Color.RED));
        wordList.add(new WriteWord(300, 6023, "2020-11-03", f, Color.RED));
//        for (int i = 0; i < 10; i++) {
//        }

        File srcImgFile = new File(src);//得到文件
        Image srcImg = ImageIO.read(srcImgFile);//文件转化为图片
        byte[] bytes = ImageUtil.addWaterMark(srcImg, wordList, "png");

        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        Thumbnails.of(new ByteArrayInputStream(bytes)).scale(0.6f).outputQuality(1).toOutputStream(bos);

//        AliImageUtil.zoomImage(new ByteArrayInputStream(bytes), bos, 2000);


        FileOutputStream outImgStream = new FileOutputStream(target);
        outImgStream.write(bos.toByteArray());
        System.out.println("添加水印完成");
        outImgStream.flush();
        outImgStream.close();

        WordConfig personal = new WordConfig(
                27,"仿宋",
                260, 505,
                300, 560,
                300, 5885,
                300, 5750,
                300, 5953,
                0, 0
        );
        WordConfig ent = new WordConfig(
                27,"仿宋",
                260, 505,
                300, 560,
                300, 5885,
                300, 5750,
                300, 6023,
                320, 5953
        );
        System.out.println(JsonUtil.toJson(personal));

    }


}

@Data
@AllArgsConstructor
class WordConfig {

    private int fontSize;
    private String fontName;

    /**
     * 乙方（上）
     */
    private int upNameX;
    private int upNameY;
    /**
     * 电话号码（上）
     */
    private int upPhoneX;
    private int upPhoneY;
    /**
     * 乙方（下）
     */
    private int downNameX;
    private int downNameY;
    /**
     * 日期1
     */
    private int downDate1X;
    private int downDate1Y;
    /**
     * 日期2
     */
    private int downDate2X;
    private int downDate2Y;
    /**
     * 法人
     */
    private int legalNameX;
    private int legalNameY;
}
